const app = getApp()

Page({
  data: {
    goodsList: [],
    cart: {},
    totalQuantity: 0,
    totalAmount: 0,
    showCartDetail: false,
    selectedAddress: null
  },
  onLoad() {
    // 页面加载时初始化数据
    this.getGoodsList()
    // 延迟检查用户类型，避免可能的循环重定向
    setTimeout(() => {
      this.checkUserType()
    }, 200)
  },
  checkUserType() {
    // 检查用户类型，如果是经销商则跳转到经销商页面
    if (app.globalData.userType === 'dealer') {
      // 使用navigateTo替代redirectTo，避免页面生命周期问题
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/dealer/orders'
        })
      }, 100)
    }
  },
  getGoodsList() {
    // 获取商品列表，使用模拟数据
    try {
      // 模拟商品数据
      const mockGoods = [
        { id: 1, name: '商品A', price: 99.00, image: '/assets/tab/goods.png' },
        { id: 2, name: '商品B', price: 199.00, image: '/assets/tab/goods.png' },
        { id: 3, name: '商品C', price: 299.00, image: '/assets/tab/goods.png' }
      ]
      
      setTimeout(() => {
        this.setData({goodsList: mockGoods}, () => {
          this.calculateCartSummary()
        })
      }, 500)
    } catch (error) {
      console.error('获取商品列表失败:', error)
      this.setData({goodsList: []})
    }
  },
  updateCart(id, quantity) {
    const cart = {...this.data.cart}
    if (quantity <= 0) {
      delete cart[id]
    } else {
      cart[id] = quantity
    }
    this.setData({cart}, () => {
      this.calculateCartSummary()
    })
  },

  calculateCartSummary() {
    const { cart, goodsList } = this.data
    let totalQuantity = 0
    let totalAmount = 0
    
    goodsList.forEach(goods => {
      const quantity = cart[goods.id] || 0
      if (quantity > 0) {
        totalQuantity += quantity
        totalAmount += goods.price * quantity
      }
    })
    
    this.setData({
      totalQuantity,
      totalAmount: parseFloat(totalAmount.toFixed(2))
    })
  },

  showCartDetail() {
    this.setData({
      showCartDetail: true
    })
  },

  hideCartDetail() {
    this.setData({
      showCartDetail: false
    })
  },

  clearCart() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空购物车吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            cart: {},
            totalQuantity: 0,
            totalAmount: 0,
            showCartDetail: false
          })
          wx.showToast({
            title: '购物车已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  goToCheckout() {
    if (this.data.totalQuantity === 0) {
      wx.showToast({
        title: '请先添加商品到购物车',
        icon: 'none'
      })
      return
    }
    
    // 跳转到地址选择页面，并设置回调
    wx.navigateTo({
      url: '/pages/user/address?selectMode=true'
    })
  },
  
  onShow() {
    // 页面显示时检查是否有选择的地址
    if (this.data.selectedAddress) {
      this.selectAddress(this.data.selectedAddress)
    }
  },
  
  // 选择地址回调方法
  selectAddress(selectedAddress) {
    wx.showModal({
      title: '确认结算',
      content: `收货地址：${selectedAddress.province}${selectedAddress.city}${selectedAddress.district}${selectedAddress.detail}
收货人：${selectedAddress.name} ${selectedAddress.phone}

共 ${this.data.totalQuantity} 件商品，总计 ¥${this.data.totalAmount}`,
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '结算成功',
            icon: 'success'
          })
          // 清空购物车和选择的地址
          this.setData({
            cart: {},
            totalQuantity: 0,
            totalAmount: 0,
            showCartDetail: false,
            selectedAddress: null  // 清空选择的地址
          })
        } else {
          // 用户取消结算时也清空选择的地址
          this.setData({
            selectedAddress: null
          })
        }
      },
      complete: () => {
        // 确保无论如何都清空选择的地址
        this.setData({
          selectedAddress: null
        })
      }
    })
  },
  increase(e) {
    const id = e.currentTarget.dataset.id
    const quantity = (this.data.cart[id] || 0) + 1
    this.updateCart(id, quantity)
  },
  decrease(e) {
    const id = e.currentTarget.dataset.id
    const quantity = Math.max(0, (this.data.cart[id] || 0) - 1)
    this.updateCart(id, quantity)
  }
})